<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="商品名称" prop="pName">
        <el-input
          v-model="queryParams.pName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="类型" prop="cName">-->
<!--        <el-input-->
<!--          v-model="queryParams.cName"-->
<!--          placeholder="请输入类型名称"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="当前价格" prop="newPrice">
        <el-input
          v-model="queryParams.newPrice"
          placeholder="请输入当前价格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="库存" prop="stock">
        <el-input
          v-model="queryParams.stock"
          placeholder="请输入库存"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:products:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:products:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:products:remove']"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-medal-1"-->
<!--          size="mini"-->
<!--          @click="handleRecommend"-->
<!--          v-hasPermi="['product:products:export']"-->
<!--        >设为推荐</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品名称" align="center" prop="pName" />
      <el-table-column label="商品图片" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="类型名称" align="center" prop="cName" />
        <el-table-column label="当前价格" align="center" prop="newPrice" />
      <el-table-column label="销量" align="center" prop="saleVolum" />
<!--      <el-table-column label="过去价格" align="center" prop="oldPrice" />-->
      <el-table-column label="库存" align="center" prop="stock" />
      <el-table-column label="商品状态" align="center" prop="type" />
<!--      <el-table-column label="创建时间" align="center" prop="createdTime" width="180">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="更新时间" align="center" prop="updatedTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:products:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:products:remove']"
          >删除</el-button>
          <template v-if="scope.row.recommend === 1">
            <span style="color: #67c23a; padding-left: 10px">已推荐</span>
          </template>
          <template v-else-if="scope.row.recommend === 0">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-medal-1"
              @click="handleRecommend(scope.row)"
              v-hasPermi="['product:products:recommend']"
            >推荐商品</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="pName">
          <el-input v-model="form.pName" placeholder="请输入商品名称" />
        </el-form-item>
<!--        这里通过选项框的形式拿到数据 具体看方法区getAllCategoriesName方法部分-->
        <el-form-item label="商品类型" prop="categories">
          <el-select v-model="form.cName" placeholder="请选择下拉选择" clearable>
            <el-option v-for="c in categories" :key="c.name" :label="c.name"
                       :value="c.name" ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商品图片" prop="image">
          <image-upload v-model="form.image"/>
        </el-form-item>
<!--        <el-form-item label="类型id" prop="cId">-->
<!--          <el-input v-model="form.cId" placeholder="请输入类型id" />-->
<!--        </el-form-item>-->

<!--        <el-form-item label="课程标签:" prop="tags">-->
<!--          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>-->
<!--          <div style="margin: 15px 0;"></div>-->
<!--          <el-checkbox-group v-model="ruleForm.tags" @change="handleCheckedCitiesChange">-->
<!--            <el-checkbox v-for="t in tags" :label="t.name" :key="t.name">{{t.name}}</el-checkbox>-->
<!--          </el-checkbox-group>-->
<!--        </el-form-item>-->

        <el-form-item label="描述信息" prop="description">
          <el-input v-model="form.description" placeholder="请输入描述信息" />
        </el-form-item>
        <el-form-item label="商品价格" prop="newPrice">
          <el-input v-model="form.newPrice" placeholder="请输入当前价格" />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input v-model="form.stock" placeholder="请输入库存" />
        </el-form-item>

<!--        <el-form-item label="创建时间" prop="createdTime">-->
<!--          <el-date-picker clearable-->
<!--                          v-model="form.createdTime"-->
<!--                          type="date"-->
<!--                          value-format="yyyy-MM-dd"-->
<!--                          placeholder="请选择创建时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="更新时间" prop="updatedTime">-->
<!--          <el-date-picker clearable-->
<!--                          v-model="form.updatedTime"-->
<!--                          type="date"-->
<!--                          value-format="yyyy-MM-dd"-->
<!--                          placeholder="请选择更新时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="销量" prop="saleVolum">-->
<!--          <el-input v-model="form.saleVolum" placeholder="请输入销量" />-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProducts, getProducts, delProducts, addProducts, updateProducts,  UserlistProducts,
  getAllCategoriesName, recommendProducts} from "@/api/product/products";
// 获取到用户信息
import store from "@/store";
import recommend from "@/views/product/recommend/index.vue";
export default {
  name: "Products",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      names:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品列表表格数据
      productsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 获取当前用户身份
      role: store.getters.roles,

      categories:[],
      // 查询参数
      queryParams: {
        // 拿到当前用户id
        userId: store.state.user.id,
        pId:null,
        pageNum: 1,
        pageSize: 10,
        pName: null,
        cName: null,
        image: null,
        newPrice: null,
        saleVolum: null,
        stock: null,
        type: null,
        // createdTime: null,
        updatedTime: null,
        recommend:null,
      },
      // 表单参数
      form: {
        categories:[],
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.init()
  },
  methods: {
    // 异步获得所有类型名称
    async init(){
      try {
        const res = await getAllCategoriesName();
        if (res && res.rows) {
          this.categories = res.rows.map(item => ({
            name: item.name,
            disabled:false, // 如果需要 disabled 属性，设置默认值
          }));
        }
      } catch (error) {
        console.error('获取类别失败', error);
      }
      // var _this = this
      // getAllCategoriesName().then(res=>{
      //   _this.categories = res.data
      //   console.log(_this.categories)
      // })
    },
    /** 查询商品列表列表 */
    // 通过判断用户身份决定是查所有还是查部分
    getList() {
      this.loading = true;
      if (this.role == 'admin' || this.role == 'commonAdmin'){
        listProducts(this.queryParams).then(response => {
          this.productsList = response.rows;
          console.log(this.productsList);
          this.total = response.total;
          this.loading = false;
        });
      }else {
        UserlistProducts(this.queryParams).then(response =>{
          this.productsList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
      }

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        pId: null,
        // name: null,
        description: null,
        newPrice: null,
        stock: null,
        image: null,
        type: null,
        createdTime: null,
        updatedTime: null,
        saleVolum: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.pId)
      this.names = selection.map(item => item.pName)
      console.log(this.names);
      console.log(this.ids);
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品列表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const pId = row.pId || this.ids
      console.log(pId);
      getProducts(pId).then(response => {
        this.form = response.data;
        console.log(this.form)
        this.open = true;
        this.title = "修改商品列表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 因为form表中有categories字段，而在新建的vo中该字段名叫cName 不一样会报错
          // 深拷贝表单 避免修改原始数据
          // 提交时提交在此处建的表单
          const submitData ={
            ...this.form,
            // 新增的时候 categories有值 修改的时候 如果没改变商品类型 为cName
            cName: this.form.categories || this.form.cName,
            userId: this.queryParams.userId
          };
          delete submitData.categories;//删除原始字段 避免干扰
          // 修改走这里
          if (this.form.pId != null) {
            console.log(submitData)
            updateProducts(submitData).then(response => {
              // console.log(submitData)
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // 新增走这里
            console.log(submitData)
            addProducts(submitData).then(response => {
              // console.log(this.form)
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const pId = row.pId || this.ids;
      const pName = row.pName || this.names
      this.$modal.confirm('是否确认删除商品名称为"' + pName + '"的数据项？').then(function() {
        return delProducts(pId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    // handleExport() {
    //   this.download('product/products/export', {
    //     ...this.queryParams
    //   }, `products_${new Date().getTime()}.xlsx`)
    // }

    handleRecommend(row){
      const pId = row.pId;
      const pName = row.pName;
      console.log(pId);
      this.$modal.confirm('是否将商品'+pName+'设为推荐？').then(function (){
        return recommendProducts(pId);
      }).then(()=>{
        this.getList();
        this.$modal.msgSuccess("设置成功")
      }).catch(()=>{})
    }
  }
};
</script>
